#include "kv_store.h"

RBTreeNode *g_rbtree;

static int compareChar(void* a, void* b)
{
    const char* str_a = *((const char**)a);
    const char* str_b = *((const char**)b);
    return strcmp(str_a, str_b); 
}

void recursion_traverse(RBTreeNode *root)
{
    if (root == NIL)
    {
        return;
    }

    if (root != NIL)
    {
        printf("key: %s,parent: %s,position: %d,color: %d\n",
               (char *)root->pkey,
               (char *)root->pParentNode->pkey,
               ((char *)root->pParentNode->pLChild->pkey == (char *)root->pkey) ? 0 : 1,
               root->color);
    }

    recursion_traverse(root->pLChild);
    recursion_traverse(root->pRChild);
}

int kvs_rbtree_create()
{
    rbtree_initNIL();
    g_rbtree = NIL;
    g_compare = compareChar;
	return 0;
}

int kvs_rbtree_free(RBTreeNode **rbtree)
{
    while ((*rbtree) != NIL)
    {
        rbtree_delete_node(rbtree,*rbtree);
    }
	return 0;
}

char *kvs_rbtree_get(RBTreeNode *rbtree, char *key)
{
    RBTreeNode * node = rbtree_search(rbtree,&key);

#ifdef PRINTFCMODE 
    recursion_traverse(rbtree);
#endif

    if (node == NIL)
    {
        return NULL;
    }
    else
    {
        return (char *)node->pvalue;
    }
}

int kvs_rbtree_set(RBTreeNode **rbtree, char *key, char *value)
{
    char *k = (char*)malloc(sizeof(char) * 1024);
    char *v = (char*)malloc(sizeof(char) * 1024);
    memcpy(k,key,sizeof(key));
    memcpy(v,value,sizeof(value));

    int res = rbtree_insert_node(rbtree,&k,v);
#ifdef PRINTFCMODE 
    recursion_traverse(*rbtree);
#endif
    return res;
}

int kvs_rbtree_mod(RBTreeNode *rbtree, char *key, char *value)
{
    RBTreeNode * node = rbtree_search(rbtree,&key);
    if (node == NIL)
    {
        return -1;
    }
    memcpy(node->pvalue,value,sizeof(value));
    return 0;
}

int kvs_rbtree_del(RBTreeNode **rbtree, char *key)
{
    RBTreeNode * node = rbtree_search(*rbtree,&key);
    if (node == NIL)
    {
        return -1;
    }
    
    return rbtree_delete_node(rbtree,node);
}

int kvs_rbtree_exist(RBTreeNode *rbtree, char *key)
{
    if (rbtree == NULL ||rbtree == NIL || key == NULL)
    {
        return -1;
    }
    
    RBTreeNode * node = rbtree_search(rbtree,&key);
    if (node == NIL)
    {
        return 0;
    }
    return 1;
}
